<template>
  <div class="orders-management">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>订单管理</h1>
      <p>管理积分购买订单和VIP购买订单</p>
    </div>

    <!-- 订单统计 -->
    <el-row :gutter="20" class="stats-row">
      <el-col :span="6" :xs="12">
        <div class="data-card">
          <div class="value">{{ stats.totalOrders }}</div>
          <div class="label">总订单数</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card success">
          <div class="value">{{ stats.paidOrders }}</div>
          <div class="label">已支付订单</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card warning">
          <div class="value">{{ stats.pendingOrders }}</div>
          <div class="label">待支付订单</div>
        </div>
      </el-col>
      
      <el-col :span="6" :xs="12">
        <div class="data-card info">
          <div class="value">¥{{ formatNumber(stats.totalAmount) }}</div>
          <div class="label">总交易金额</div>
        </div>
      </el-col>
    </el-row>

    <!-- 搜索工具栏 -->
    <div class="toolbar">
      <el-form :model="searchForm" class="search-form" inline>
        <el-form-item label="订单号">
          <el-input v-model="searchForm.orderNo" placeholder="请输入订单号" clearable />
        </el-form-item>
        <el-form-item label="用户ID">
          <el-input v-model="searchForm.userId" placeholder="请输入用户ID" clearable />
        </el-form-item>
        <el-form-item label="订单类型">
          <el-select v-model="searchForm.orderType" placeholder="请选择订单类型" clearable>
            <el-option label="全部" value="" />
            <el-option label="积分订单" value="credits" />
            <el-option label="VIP订单" value="vip" />
          </el-select>
        </el-form-item>
        <el-form-item label="订单状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="全部" value="" />
            <el-option label="待支付" value="pending" />
            <el-option label="已支付" value="paid" />
            <el-option label="已取消" value="cancelled" />
            <el-option label="已退款" value="refunded" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
      
      <div class="toolbar-actions">
        <el-button type="success" @click="handleExport">
          <el-icon><Download /></el-icon>
          导出
        </el-button>
        <el-button type="primary" @click="handleRefresh">
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 订单列表 -->
    <div class="content-card">
      <el-table :data="orderList" :loading="loading" stripe style="width: 100%">
        <el-table-column prop="orderNo" label="订单号" width="180" />
        <el-table-column prop="userId" label="用户ID" width="80" />
        <el-table-column prop="orderType" label="订单类型" width="100">
          <template #default="scope">
            <el-tag :type="scope.row.orderType === 'credits' ? 'primary' : 'warning'" size="small">
              {{ scope.row.orderType === 'credits' ? '积分订单' : 'VIP订单' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="productName" label="商品名称" width="150" />
        <el-table-column prop="amount" label="订单金额" width="100">
          <template #default="scope">
            ¥{{ scope.row.amount }}
          </template>
        </el-table-column>
        <el-table-column prop="paymentMethod" label="支付方式" width="100">
          <template #default="scope">
            {{ getPaymentMethodText(scope.row.paymentMethod) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)" size="small">
              {{ getStatusText(scope.row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createTime) }}
          </template>
        </el-table-column>
        <el-table-column prop="paidTime" label="支付时间" width="180">
          <template #default="scope">
            {{ scope.row.paidTime ? formatDate(scope.row.paidTime) : '-' }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <el-button size="small" @click="handleViewOrder(scope.row)">
              <el-icon><View /></el-icon>
              详情
            </el-button>
            <el-dropdown v-if="scope.row.status === 'pending'" @command="(cmd: string) => handleOrderAction(cmd, scope.row)">
              <el-button size="small" type="warning">
                操作<el-icon class="el-icon--right"><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cancel">取消订单</el-dropdown-item>
                  <el-dropdown-item command="mockPay">模拟支付</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
            <el-button v-else-if="scope.row.status === 'paid'" size="small" type="danger" @click="handleRefund(scope.row)">
              退款
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :page-sizes="[10, 20, 50, 100]"
        :total="pagination.total"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        class="pagination"
      />
    </div>

    <!-- 订单详情弹窗 -->
    <el-dialog v-model="orderDetailVisible" title="订单详情" width="600px">
      <el-descriptions v-if="currentOrder" :column="2" border>
        <el-descriptions-item label="订单号">{{ currentOrder.orderNo }}</el-descriptions-item>
        <el-descriptions-item label="用户ID">{{ currentOrder.userId }}</el-descriptions-item>
        <el-descriptions-item label="订单类型">
          <el-tag :type="currentOrder.orderType === 'credits' ? 'primary' : 'warning'" size="small">
            {{ currentOrder.orderType === 'credits' ? '积分订单' : 'VIP订单' }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="商品名称">{{ currentOrder.productName }}</el-descriptions-item>
        <el-descriptions-item label="订单金额">¥{{ currentOrder.amount }}</el-descriptions-item>
        <el-descriptions-item label="实付金额">{{ currentOrder.paidAmount ? '¥' + currentOrder.paidAmount : '-' }}</el-descriptions-item>
        <el-descriptions-item label="支付方式">{{ getPaymentMethodText(currentOrder.paymentMethod) }}</el-descriptions-item>
        <el-descriptions-item label="订单状态">
          <el-tag :type="getStatusType(currentOrder.status)" size="small">
            {{ getStatusText(currentOrder.status) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="创建时间">{{ formatDate(currentOrder.createTime) }}</el-descriptions-item>
        <el-descriptions-item label="支付时间">{{ currentOrder.paidTime ? formatDate(currentOrder.paidTime) : '-' }}</el-descriptions-item>
        <el-descriptions-item label="第三方订单号" :span="2">{{ currentOrder.thirdPartyOrderNo || '-' }}</el-descriptions-item>
        <el-descriptions-item label="备注" :span="2">{{ currentOrder.remark || '-' }}</el-descriptions-item>
      </el-descriptions>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrderStats, getOrderList, cancelOrder, refundOrder } from '@/api'

// 响应式数据
const loading = ref(false)
const orderList = ref<any[]>([])
const orderDetailVisible = ref(false)
const currentOrder = ref<any>(null)

// 统计数据
const stats = reactive({
  totalOrders: 0,
  paidOrders: 0,
  pendingOrders: 0,
  totalAmount: 0
})

// 搜索表单
const searchForm = reactive({
  orderNo: '',
  userId: '',
  orderType: '',
  status: ''
})

// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 加载订单统计
const loadOrderStats = async () => {
  try {
    const response = await getOrderStats()
    if (response && response.success) {
      Object.assign(stats, response.data)
    }
  } catch (error) {
    console.error('Load order stats failed:', error)
    // 保持默认值0
  }
}

// 加载订单列表
const loadOrderList = async () => {
  loading.value = true
  try {
    const params = {
      current: pagination.page,
      size: pagination.size,
      orderNo: searchForm.orderNo || undefined,
      userId: searchForm.userId || undefined,
      orderType: searchForm.orderType || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await getOrderList(params)
    
    if (response && response.success) {
      orderList.value = response.data?.data || []
      pagination.total = response.data?.total || 0
    } else {
      orderList.value = []
      pagination.total = 0
      ElMessage.warning(response?.message || '获取订单列表失败')
    }
  } catch (error) {
    console.error('Load order list failed:', error)
    ElMessage.error('加载订单列表失败')
    orderList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  pagination.page = 1
  loadOrderList()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    (searchForm as any)[key] = ''
  })
  pagination.page = 1
  loadOrderList()
}

// 导出
const handleExport = async () => {
  try {
    // 获取所有订单数据用于导出
    const params = {
      current: 1,
      size: 999999,
      orderNo: searchForm.orderNo || undefined,
      userId: searchForm.userId || undefined,
      orderType: searchForm.orderType || undefined,
      status: searchForm.status || undefined
    }
    
    const response = await getOrderList(params)
    const data = response.data?.data || []
    
    if (data.length === 0) {
      ElMessage.warning('没有数据可导出')
      return
    }
    
    exportOrdersToCSV(data)
    ElMessage.success(`成功导出 ${data.length} 条订单`)
  } catch (error) {
    ElMessage.error('导出失败')
  }
}

// CSV导出函数
const exportOrdersToCSV = (data: any[]) => {
  const headers = ['订单号', '用户ID', '订单类型', '商品名称', '订单金额', '实付金额', '支付方式', '订单状态', '创建时间', '支付时间', '第三方订单号', '备注']
  const csvContent = [
    headers.join(','),
    ...data.map(order => [
      order.orderNo || '',
      order.userId || '',
      order.orderType === 'credits' ? '积分订单' : 'VIP订单',
      order.productName || '',
      order.amount || 0,
      order.paidAmount || 0,
      getPaymentMethodText(order.paymentMethod),
      getStatusText(order.status),
      formatDate(order.createTime),
      formatDate(order.paidTime),
      order.thirdPartyOrderNo || '',
      order.remark || ''
    ].join(','))
  ].join('\n')
  
  const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `订单数据_${new Date().getTime()}.csv`
  link.click()
}

// 刷新
const handleRefresh = () => {
  loadOrderList()
}

// 查看订单详情
const handleViewOrder = (order: any) => {
  currentOrder.value = order
  orderDetailVisible.value = true
}

// 订单操作
const handleOrderAction = async (command: string, order: any) => {
  const actions: Record<string, { text: string; type: 'warning' | 'info'; api: any }> = {
    cancel: { text: '取消订单', type: 'warning', api: cancelOrder },
    mockPay: { text: '模拟支付', type: 'info', api: null }
  }
  
  const action = actions[command]
  if (!action) return
  
  try {
    await ElMessageBox.confirm(`确定要${action.text}吗？`, '确认操作', {
      type: action.type
    })
    
    if (command === 'cancel' && action.api) {
      const response = await action.api(order.id)
      if (response && response.success) {
        ElMessage.success(`${action.text}成功`)
        loadOrderList()
        loadOrderStats() // 刷新统计数据
      } else {
        ElMessage.error(response?.message || `${action.text}失败`)
      }
    } else if (command === 'mockPay') {
      // 模拟支付功能
      ElMessage.info('模拟支付功能开发中...')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(`${action.text}失败`)
    }
  }
}

// 退款
const handleRefund = async (order: any) => {
  try {
    const { value: reason } = await ElMessageBox.prompt('请输入退款原因', '确认退款', {
      confirmButtonText: '确认退款',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入退款原因（可选）',
      inputType: 'textarea'
    })
    
    const response = await refundOrder(order.id, { 
      reason: reason || '管理员操作退款',
      amount: order.paidAmount || order.amount 
    })
    
    if (response && response.success) {
      ElMessage.success('退款成功')
      loadOrderList()
      loadOrderStats() // 刷新统计数据
    } else {
      ElMessage.error(response?.message || '退款失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('退款失败')
    }
  }
}

// 分页处理
const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadOrderList()
}

const handleCurrentChange = (page: number) => {
  pagination.page = page
  loadOrderList()
}

// 工具函数
const formatNumber = (num: number) => {
  return num.toLocaleString()
}

const formatDate = (date: Date | string) => {
  if (!date) return '-'
  const d = new Date(date)
  return d.toLocaleString('zh-CN')
}

const getStatusType = (status: string) => {
  const types: Record<string, string> = {
    pending: 'warning',
    paid: 'success',
    cancelled: 'info',
    refunded: 'danger'
  }
  return types[status] || ''
}

const getStatusText = (status: string) => {
  const texts: Record<string, string> = {
    pending: '待支付',
    paid: '已支付',
    cancelled: '已取消',
    refunded: '已退款'
  }
  return texts[status] || status
}

const getPaymentMethodText = (method: string) => {
  const texts: Record<string, string> = {
    wechat: '微信支付',
    alipay: '支付宝'
  }
  return texts[method] || method
}

// 页面加载
onMounted(() => {
  loadOrderStats()
  loadOrderList()
})
</script>

<style scoped>
.orders-management {
  padding: 0;
}

.stats-row {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  justify-content: center;
}
</style>
